<template>
	<view class="container">
		<BackGround />

		<Header title="请确认照片" />
		<view class="imageList" v-if="previewUrlObjList.length == 1">
			<view class="preViewImage center" v-for="(item, index) in previewUrlObjList" :key="index">
				<image :src="item.preview" mode="widthFix" v-if="!item.uploadSuccessPath" class="mainImage"></image>
				<image :src="item.uploadSuccessPath" mode="widthFix" v-else class="mainImage" @click="selectImage(item.uploadSuccessPath)"></image>

				<view class="preViewImage-mask" v-if="!item.uploadSuccessPath">
					<view style="position: relative; width: 91vw; height: 100vw">
						<Loading size="large" />
					</view>
				</view>

				<view class="sel" v-if="selImage == item.uploadSuccessPath">
					<image src="/static/preview-sel.png" mode="widthFix" class="preview-sel-icon"></image>
				</view>
			</view>
		</view>

		<view class="imageLists" v-if="previewUrlObjList.length == 2">
			<view class="preViewImage center" v-for="(item, index) in previewUrlObjList" :key="index">
				<image :src="item.preview" mode="widthFix" v-if="!item.uploadSuccessPath" class="mainImage"></image>
				<image :src="item.uploadSuccessPath" mode="widthFix" v-else class="mainImage"></image>

				<view class="preViewImage-mask" v-if="!item.uploadSuccessPath">
					<view style="position: relative; width: 44vw; height: 48vw">
						<Loading size="small" />
					</view>
				</view>

				<view class="sel" v-if="selImage == item.uploadSuccessPath">
					<image src="/static/preview-sel.png" mode="widthFix" class="preview-sel-icon"></image>
				</view>
			</view>
		</view>
		<!-- <view class="preViewImage center">
			<image :src="previewImage" mode="widthFix" v-if="!resultImage"></image>
			<image :src="resultImage" mode="widthFix" v-else @click="preview(resultImage)"></image>
		</view> -->

		<view class="confirm-order center" hover-class="hoverClass" hover-stay-time=".3s" @click="confirmProduct" v-if="!loading">确认制作产品</view>
		<view class="retry center" hover-class="hoverClass" hover-stay-time=".3s" @click="addImage" v-if="!loading">再拍一张</view>

		<ShowQrCode ref="showQrCodeRef" />
	</view>
</template>

<script setup>
import CryptoJS from 'crypto-js';
import moment from 'moment';
import OSS from 'ali-oss';
import { http } from 'uview-plus';
import { httpConfig } from '@/utils/env.js';
import Header from '@/components/Header.vue';
import Loading from '@/components/Loading.vue';
import ShowQrCode from '@/components/ShowQrCode.vue';
import { computed, ref } from 'vue';
import { onLoad, onUnload } from '@dcloudio/uni-app';

const showQrCodeRef = ref();
const previewUrlObjList = ref([]);
const selImage = ref();

const templateId = ref('');
const productList = ref([]);

const resultImage = ref();
const queryTimes = ref(0);

function preview(url) {
	uni.previewImage({
		urls: previewUrlObjList.value,
		current: 0
	});
}

const loading = computed(() => {
	let index = previewUrlObjList.value.findIndex((item) => !item.uploadSuccessPath);
	if (index > -1) {
		return true;
	} else {
		return false;
	}
});

async function getOssStsToken() {
	return new Promise((resolve, reject) => {
		uni.request({
			url: httpConfig.uploadUrl + '/common/getOssStsToken',
			method: 'GET',
			success: (res) => {
				resolve(res.data);
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
}

function generatePolicyAndSignature(key, accessKeySecret, securityToken) {
	try {
		// 设置policy过期时间（1小时后）
		const expiration = new Date(Date.now() + 3600 * 1000).toISOString();

		// 构建policy
		const policyText = {
			expiration: expiration,
			conditions: [
				['content-length-range', 0, 10485760], // 10MB限制
				['starts-with', '$key', key.substring(0, key.lastIndexOf('/') + 1)] // 限制上传路径
			]
		};

		// Base64编码policy
		const policyBase64 = btoa(JSON.stringify(policyText));

		// 生成signature
		const signature = hmacSha1(policyBase64, accessKeySecret);

		return {
			policy: policyBase64,
			signature: signature
		};
	} catch (error) {
		console.error('生成policy和signature失败:', error);
		throw error;
	}
}

// HMAC-SHA1签名（使用crypto-js标准实现）
function hmacSha1(message, key) {
	try {
		// 使用crypto-js生成HMAC-SHA1签名
		const hash = CryptoJS.HmacSHA1(message, key);
		const signature = CryptoJS.enc.Base64.stringify(hash);
		return signature;
	} catch (error) {
		console.error('HMAC-SHA1签名生成失败:', error);
		throw error;
	}
}

// 循环上传图片
function uploadFiles(filePath, ossConfig) {
	return new Promise(async (resolve, reject) => {
		console.log('filePath===========', filePath);

		let date = new Date();
		let dateFormat = moment(date).format('YYYY-MM-DD');

		let list = filePath.split('/');
		const key = `generate/image/${dateFormat}/${list[list.length - 1]}`;
		console.log('key===============', key);

		const { policy, signature } = generatePolicyAndSignature(key, ossConfig.accessKeySecret, ossConfig.securityToken);
		console.log('policy===============', policy, signature);

		const formData = {
			key, // OSS 存储路径
			policy, // 留空（STS 方式无需）
			OSSAccessKeyId: ossConfig.accessKeyId,
			signature, // 留空（STS 方式无需）
			'x-oss-security-token': ossConfig.securityToken, // 关键参数！
			success_action_status: '200' // 成功响应码
		};

		uni.uploadFile({
			url: 'https://instant-pix.oss-cn-shenzhen.aliyuncs.com', // OSS Bucket 地址
			filePath: filePath,
			name: 'file', // 必须为 'file'
			formData,
			header: {
				'Content-Type': 'multipart/form-data' // 重要！
			},
			success: (res) => {
				console.log('uploadFilesres==========', res);
				if (res.statusCode == 200) {
					const fileUrl = `https://instant-pix.oss-cn-shenzhen.aliyuncs.com/${key}`;
					resolve(fileUrl);
				} else {
					resolve('');
				}
			},
			fail: (err) => {
				console.log('uploadFilesError==========', err);
				reject(err);
			}
		});
	});
}

async function uploadImages(urls) {
	console.log('urls==========', urls);
	// 获取阿里oss上传秘钥
	const ossTokenRes = await getOssStsToken();

	console.log('ossTokenRes===========', ossTokenRes);

	// 循环上传
	const uploadPromises = urls.map((file) => {
		return uploadFiles(file, ossTokenRes.data);
	});

	const uploadSuccessRes = await Promise.all(uploadPromises);

	console.log('uploadSuccessRes==========', uploadSuccessRes);

	createAiImage(uploadSuccessRes);
}

async function createAiImage(imagesUrl) {
	try {
		const { data } = await http.post(`/open/api/model/createAiImage`, {
			imagesUrl: imagesUrl.join(','),
			deviceSn: '12345666',
			templateId: templateId.value
		});

		console.log('createAiImageRes', data);

		setTimeout(() => {
			getAiImage(data);
		}, 10000);
	} catch (e) {
		console.log('createAiImageReject', e);
	} finally {
	}
}

async function getAiImage(taskSn) {
	const { data } = await http.get(`/open/api/model/queryTask?taskSn=${taskSn}`);
	if (data.status !== 2) {
		if (queryTimes.value < 10) {
			setTimeout(() => {
				queryTimes.value++;
				getAiImage(taskSn);
			}, 3000);
		} else {
			uni.showModal({
				title: '提示',
				content: '图片生成失败，请重新拍摄',
				showCancel: false,
				confirmText: '确定',
				success: (res) => {
					if (res.confirm) {
						uni.navigateBack();
					}
				}
			});
		}
	} else {
		// resultImage.value = data.imagesUrlList[0];
		previewUrlObjList.value[previewUrlObjList.value.length - 1].uploadSuccessPath = data.imagesUrlList[0];
	}
}

function addImage() {
	uni.navigateTo({
		url: `/pages/makePhoto/index?templateId=${templateId.value}&type=edit`
	});
}

function selectImage(url) {
	// let index = selectImageList.value.indexOf(url);
	// if (index > -1) {
	// 	selectImageList.value.splice(index, 1);
	// } else {
	// 	selectImageList.value.push(url);
	// }
	selImage.value = url;
}

async function confirmProduct() {
	if (!selImage.value) {
		uni.showToast({
			title: '请选择图片',
			icon: 'none'
		});
		return;
	}
	uni.showLoading({
		title: '生成中...'
	});
	const { data } = await http.post(`/open/api/model/createOrder`, {
		imagesUrl: [selImage.value],
		deviceSn: '12345666',
		templateId: templateId.value,
		printProductIdList: productList.value
	});

	console.log('orderNo===========', data);

	showQrCodeRef.value.init(data.scanCodeBase64, data.orderSn);
	uni.hideLoading();
}

onLoad((options) => {
	productList.value = JSON.parse(options.productList);
	templateId.value = options.templateId;

	let previewImage = JSON.parse(options.previewImage || '[]');

	if (previewImage && previewImage.length) {
		const list = (previewImage || []).map((item) => {
			return {
				preview: item,
				uploadSuccessPath: ''
			};
		});
		previewUrlObjList.value = previewUrlObjList.value.concat(list);
		uploadImages(previewImage);
	}

	// 测试代码 start
	// previewImage = ['https://instant-pix.oss-cn-shenzhen.aliyuncs.com/1755456348032_epii_tmp_1755455174355.jpg'];
	// previewUrlObjList.value = previewImage.map((item) => {
	// 	return {
	// 		preview: item,
	// 		uploadSuccessPath: ''
	// 	};
	// });
	// previewUrlObjList.value.push({
	// 	preview: 'https://instant-pix.oss-cn-shenzhen.aliyuncs.com/1755456348032_epii_tmp_1755455174355.jpg',
	// 	uploadSuccessPath: ''
	// });
	// createAiImage(previewImage);
	// 测试代码 end

	uni.$on('updateImage', (imgList) => {
		const list = (imgList || []).map((item) => {
			return {
				preview: item,
				uploadSuccessPath: ''
			};
		});
		previewUrlObjList.value = previewUrlObjList.value.concat(list);

		uploadImages(imgList);
	});
});

onUnload(() => {
	uni.$off('updateImage');
});
</script>

<style lang="scss" scoped>
.imageLists {
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;

	.preViewImage {
		width: 44vw;
		height: 48vw;
		border-radius: 4vw;
		overflow: hidden;
		margin: 0 auto 0.8vw;
		position: relative;
	}
}

.preViewImage {
	width: 91vw;
	height: 100vw;
	border-radius: 4vw;
	overflow: hidden;
	margin: 0 auto;
	position: relative;

	.mainImage {
		width: 100%;
	}

	.preViewImage-mask {
		width: 100%;
		height: 100%;
		background-color: rgb(0, 0, 0, 0.2);
		position: absolute;
		top: 0;
		left: 0;
		z-index: 10;
	}

	.sel {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 10;
		background-color: rgba(255, 208, 0, 0.5);

		.preview-sel-icon {
			width: 14vw;
			height: 14vw;
			position: absolute;
			top: 50%;
			left: 50%;
			z-index: 20;
			transform: translate(-50%, -50%);
		}
	}
}

.confirm-order {
	width: 91vw;
	height: 12vw;
	background: #ffd400;
	border-radius: 6vw;

	font-weight: bold;
	font-size: 4vw;
	color: #000000;
	text-align: center;
	margin: 5vw auto 0;
}

.retry {
	width: 91vw;
	height: 12vw;
	background: rgba(252, 192, 17, 0.2);
	border-radius: 6vw;

	font-weight: bold;
	font-size: 4vw;
	color: #000000;
	text-align: center;
	margin: 5vw auto 0;
}
</style>
